package com.example.apricots;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.apricots.Net.HttpClient;
import com.example.apricots.Net.HttpResponseHandlerCallback;
import com.example.apricots.Net.Request.RLogin;
import com.example.apricots.Net.ResponseCallback;
import com.example.apricots.Net.bean.CommonBean;
import com.example.apricots.bean.User;
import com.jzp.rotate3d.Rotate3D;


import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import cn.addapp.pickers.listeners.OnLinkageListener;
import cn.addapp.pickers.picker.AddressPicker;
import cn.addapp.pickers.picker.NumberPicker;
import cn.addapp.pickers.util.ConvertUtils;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ActivityLogin extends AppCompatActivity implements View.OnClickListener {

    private static final int registSuccess = 100;
    private static final int registFail = 101;
    private static final int loginSuccess = 102;
    private static final int loginFail = 103;
    private myHandler mHandler;
    private static final String TAG = ActivityLogin.class.getSimpleName();
    TextView noPassLoginTv;
    TextView txt_gender;
    TextView txt_age;
    TextView txt_height;
    TextView txt_address;
    RadioGroup rg_gender;
    LinearLayout paparent_ll;
    LinearLayout accountLoginLayout;
    LinearLayout phoneLoginLayout;
    EditText login_input_password;
    EditText login_input_name;
    EditText login_input_password_r;
    EditText login_input_name_r;
    ImageView login_hide_input;
    ImageView login_hide_input_r;
    ImageView iv_pwd_clear;
    ImageView iv_name_clear;
    ImageView iv_name_r_clear;
    Button login;
    Button register_confirm;
    boolean isclicked = false;
    Rotate3D rotate;
    User user_reg;

    private class myHandler extends Handler {
        private WeakReference<ActivityLogin> reference;

        private myHandler(ActivityLogin activityLogin) {
            reference = new WeakReference<>(activityLogin);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ActivityLogin context = reference.get();

            switch (msg.what) {
                case registSuccess:

                    Toast.makeText(context, "success 111111111", Toast.LENGTH_SHORT).show();
                    break;
                case registFail:
                    login_input_name_r.setText("");
                    login_input_password_r.setText("");
                    Toast.makeText(context, "fail 111111111111", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "handleMessage: " + "11111111111");
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initview();
        initrotate();

        /*List<User> userList=DBManager.getInstance().queryUser();
        Log.e("-----",""+userList);
        if(userList!=null)
        Log.e("获取的用户=",""+userList.size());
        for(User user:userList){
            Log.e(TAG, "onCreate: "+user );
        }*/
    }

    /**
     * 初始化旋转参数
     * paparent_ll:         父布局
     * accountLoginLayout:  子布局1
     * phoneLoginLayout:    子布局2
     */
    private void initrotate() {
        rotate = new Rotate3D.Builder(this)
                .setParentView(paparent_ll)
                .setPositiveView(accountLoginLayout)
                .setNegativeView(phoneLoginLayout)
                .create();
    }

    private void initview() {
        user_reg = new User();
        user_reg.setId(null);

        noPassLoginTv = findViewById(R.id.noPassLoginTv);
        noPassLoginTv.setOnClickListener(this);
        paparent_ll = findViewById(R.id.parent_ll);
        accountLoginLayout = findViewById(R.id.accountLoginLayout);
        phoneLoginLayout = findViewById(R.id.phoneLoginLayout);
        txt_height = findViewById(R.id.txt_height);
        txt_address = findViewById(R.id.txt_address);
        txt_age = findViewById(R.id.txt_age);
        rg_gender = findViewById(R.id.rg_gender);
        rg_gender.setOnCheckedChangeListener(genderListener);

        iv_pwd_clear = findViewById(R.id.iv_pwd_clear);
        iv_pwd_clear.setOnClickListener(this);
        iv_name_clear = findViewById(R.id.iv_name_clear);
        iv_name_clear.setOnClickListener(this);
        iv_name_r_clear = findViewById(R.id.iv_name_r_clear);
        iv_name_r_clear.setOnClickListener(this);
        login = findViewById(R.id.login);
        login.setOnClickListener(this);
        login_hide_input = findViewById(R.id.login_hide_input);
        login_hide_input.setOnClickListener(this);
        /*login_hide_input_r = findViewById(R.id.login_hide_input_r);
        login_hide_input_r.setOnClickListener(this);*/
//登陆
        login_input_name = findViewById(R.id.login_input_name);
        login_input_name.addTextChangedListener(login_name_watcher);
        login_input_name.setOnFocusChangeListener(login_name_focusListener);
        login_input_password = findViewById(R.id.login_input_password);
        login_input_password.addTextChangedListener(login_pwd_watcher);
        login_input_password.setOnFocusChangeListener(login_pwd_focusListener);
        login_input_password.setTransformationMethod(PasswordTransformationMethod.getInstance());

//注册
        login_input_name_r = findViewById(R.id.login_input_name_r);
        login_input_name_r.addTextChangedListener(login_name_r_watcher);
        login_input_password_r = findViewById(R.id.login_input_password_r);


        register_confirm = findViewById(R.id.register);
        register_confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.noPassLoginTv:
                toRegistLayout();
                break;
            case R.id.login_hide_input:
                isclicked = !isclicked;
                handlePassWord(isclicked);
                break;
            case R.id.login:
                login();
                break;
            case R.id.iv_name_clear:
                login_input_name.setText("");
                break;
            case R.id.iv_name_r_clear:
                login_input_name_r.setText("");
                break;
            case R.id.iv_pwd_clear:
                login_input_password.setText("");
                break;
            case R.id.register:
                register();
                break;
        }
    }


    /**
     * 翻转到注册界面
     */
    private void toRegistLayout() {
        rotateView();
        noPassLoginTv.setVisibility(View.GONE);
    }

    /**
     * 确认注册用户
     */
    private boolean isRegister = false;

    private void register() {

        String regist_name = login_input_name_r.getText().toString();
        String regist_pwd = login_input_password_r.getText().toString();
        if (regist_name.equals("") || regist_pwd.equals("")) {
            Toast.makeText(ActivityLogin.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        } else {
            user_reg.setUsername(regist_name);
            user_reg.setPassword(regist_pwd);
            HttpClient.addUser(user_reg, new HttpResponseHandlerCallback<>(new ResponseCallback<ResponseBody>() {
                @Override
                public void success(ResponseBody responseBody) {
                    try {
                        String source = responseBody.string();
                        JSONObject jsonObject = JSON.parseObject(source);
                        String code = jsonObject.getString("code");
                        Log.e(TAG, "onResponse: source=" + source);
                        if (code.equals("200")) {
                            //注册成功
                            isRegister = true;
                        } else {
                            //注册失败
                            isRegister = false;
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void faile() {
                    Log.e(TAG, "请求失败 ");
                    isRegister = false;
                }
            }));
            if (isRegister) {
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                toRegistLayout();

            } else {
                Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

    /**
     * 翻转两个布局
     */
    private void rotateView() {
        rotate.transform();//启用rotate3D
    }

    /**
     * 登录
     */
    private boolean isLogin = false;
    private void login() {
        String name = login_input_name.getText().toString();
        String pwd = login_input_password.getText().toString();
        RLogin rLogin = new RLogin(name, pwd);
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("password", pwd);
        String bodys = json.toJSONString();
        HttpClient.login(1, rLogin,new HttpResponseHandlerCallback<>(new ResponseCallback<ResponseBody>() {
            @Override
            public void success(ResponseBody responseBody) {
                try {
                    String source = responseBody.string();
                    JSONObject jsonObject = JSON.parseObject(source);
                    String code = jsonObject.getString("code");
                    Log.e(TAG, "onResponse: source=" + source);
                    if (code.equals("200")) {
                        Log.e(TAG, "success: 登录成功" );
                        isLogin=true;
                    } else {
                        Log.e(TAG, "fail: 登录失败" );
                        isLogin=false;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void faile() {
                Log.e(TAG, "请求失败 ");
                isLogin=false;
            }
        }));

        if(isLogin){
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this,MainActivity.class));
        }else {
            Toast.makeText(this, "登录失败，请检查网络或密码是否正确", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理登陆界面密码隐藏
     *
     * @param isclicked
     */
    private void handlePassWord(boolean isclicked) {
        if (isclicked) {
            login_input_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            login_hide_input.setImageResource(R.drawable.btn_hide_blue);
        } else {
            login_input_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            login_hide_input.setImageResource(R.drawable.btn_hide);
        }
    }


    /**
     * 用户名的watcher
     */
    TextWatcher login_name_watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            //if (!login_input_name.getText().toString().equals("")) {
            if (!editable.toString().equals("")) {
                iv_name_clear.setVisibility(View.VISIBLE);
            } else {
                iv_name_clear.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 用户名(注册)的watcher
     */
    TextWatcher login_name_r_watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            //if (!login_input_name.getText().toString().equals("")) {
            if (!editable.toString().equals("")) {
                iv_name_r_clear.setVisibility(View.VISIBLE);
            } else {
                iv_name_r_clear.setVisibility(View.GONE);
            }
        }
    };
    /**
     * 密码的watcher
     */
    TextWatcher login_pwd_watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!editable.toString().equals("")) {
                iv_pwd_clear.setVisibility(View.VISIBLE);
            } else {
                iv_pwd_clear.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 用户名的焦点监听
     */
    View.OnFocusChangeListener login_name_focusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                iv_name_clear.setVisibility(View.GONE);
            }
        }
    };
    /**
     * 密码的焦点监听
     */
    View.OnFocusChangeListener login_pwd_focusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                iv_pwd_clear.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 用户名(注册)的焦点监听
     */
    View.OnFocusChangeListener login_name_r_focusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                iv_name_clear.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 选择身高
     *
     * @param view
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void selectHeight(View view) {
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        NumberPicker picker = new NumberPicker(this);
        picker.setRange(170, 200, 1);
        picker.setLabel("CM");
        picker.setCanLoop(false);//不能循环
        picker.setWidthAndHeight((int) (width / 1.5), (int) (height / 2.5));
        picker.setTitleText("身高(CM)");
        picker.setSubmitText("确定");
        picker.setCancelText("取消");
        picker.setTopBackgroundColor(getColor(R.color.btn_gradient));
        picker.setOffset(3);
        picker.setSelectedItem(172);//加载出现的位置
        picker.setCancelVisible(true);
        picker.setTopLineVisible(true);
        picker.setLineVisible(false);
        picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                Toast.makeText(ActivityLogin.this, "index=" + index + ", item=" + item.intValue(), Toast.LENGTH_SHORT).show();
                String height = item.toString();
                txt_height.setText(height + "CM");
                user_reg.setHeight(height);
            }
        });
        picker.show();
    }

    /**
     * 选择年龄
     *
     * @param view
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void selectAge(View view) {
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        NumberPicker picker = new NumberPicker(this);
        picker.setRange(18, 188, 1);
        picker.setLabel("岁");
        picker.setCanLoop(false);//不能循环
        picker.setWidthAndHeight((int) (width / 1.5), (int) (height / 2.5));
        picker.setTitleText("年龄(岁)");
        picker.setSubmitText("确定");
        picker.setCancelText("取消");
        picker.setTopBackgroundColor(getColor(R.color.btn_gradient));
        picker.setOffset(3);
        picker.setSelectedItem(18);//加载出现的位置
        picker.setCancelVisible(true);
        picker.setTopLineVisible(true);
        picker.setLineVisible(false);
        picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                Toast.makeText(ActivityLogin.this, "index=" + index + ", item=" + item.intValue(), Toast.LENGTH_SHORT).show();
                String age = item.toString();
                txt_age.setText(age + "岁");
                user_reg.setAge(age);
            }
        });
        picker.show();
    }

    /**
     * 选择性别
     */
    RadioGroup.OnCheckedChangeListener genderListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
            switch (checkId) {
                case R.id.rb_male:
                    Toast.makeText(ActivityLogin.this, "男", Toast.LENGTH_SHORT).show();
                    String male = "男";
                    user_reg.setSex(male);
                    break;
                case R.id.rb_famale:
                    Toast.makeText(ActivityLogin.this, "女", Toast.LENGTH_SHORT).show();
                    String famale = "女";
                    user_reg.setSex(famale);
                    break;
            }
        }
    };

    /**
     * 选择家庭住址
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void addAddress(View view) {
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        try {
            ArrayList<Province> data = new ArrayList<>();
            String prvcince = ConvertUtils.toString(getAssets().open("city.json"));
            //将从json中获取的字符串转成Provice对象
            data.addAll(JSON.parseArray(prvcince, Province.class));
            AddressPicker picker = new AddressPicker(this, data);
            picker.setWidthAndHeight((int) (width), (int) (height / 2));
            picker.setHideProvince(false);
            picker.setCanLoop(false);
            picker.setTitleText("你哪个省的？");
            picker.setTopBackgroundColor(getColor(R.color.btn_gradient));
            picker.setOnLinkageListener(new OnLinkageListener() {
                @Override
                public void onAddressPicked(Province province, City city, County county) {
                    Log.e(TAG, "province : " + province + ", city: " + city + ", county: " + county);
                    StringBuilder address = new StringBuilder();
                    address.append(province.getAreaName())
                            .append(city.getAreaName())
                            .append(county.getAreaName());
                    txt_address.setText(address);
                    user_reg.setAddress(address.toString());
                }
            });
            picker.show();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendHanderMessage(int what, long delay) {
        if (mHandler != null && !mHandler.hasMessages(what)) {
            mHandler.sendEmptyMessageDelayed(what, delay);
        }
    }
}
